package com.lagou.cl.config;

import lombok.Data;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Configuration
@PropertySource(value = {"classpath:rabbit.properties"})
@ConfigurationProperties(prefix = "rabbitmq")
@Data
@EnableRabbit
public class RabbitConfig {


	private Long x_message_ttl;
	private Long x_expires;

	@Bean
	public Queue queue() {
		Map<String, Object> props = new HashMap<>();


		// 消息的生存时间 15s
		// 如果15s内未支付，则放入到死信队列中
		props.put("x-message-ttl", x_message_ttl);

		// 设置队列的空闲存活时间（如该队列根本没有消费者，一直没有使用，队列可以存活多久）
		// 60S后该队列中没有消费者，将会被删除
		props.put("x-expires", x_expires);

		// 设置该队列所关联的死信交换器（当队列消息TTL到期后依然没有消费，则加 入死信队列）
		props.put("x-dead-letter-exchange", "ex.pay.dlx");
		// 设置该队列所关联的死信交换器的routingKey，如果没有特殊指定，使用原 队列的routingKey
		props.put("x-dead-letter-routing-key", "key.pay.dlx");

		Queue queue = new Queue("queue.pay", true, false, false, props);
		return queue;
	}

	@Bean
	public Exchange exchange() {
		DirectExchange exchange = new DirectExchange("ex.pay", true, false, null);
		return exchange;
	}

	@Bean
	public Binding binding() {
		return BindingBuilder.bind(queue()).to(exchange()).with("key.pay").noargs();
	}

	/*** 死信队列 * @return */
	@Bean
	public Queue queueDlx() {
		Queue queue = new Queue("queue.pay.dlx", true, false, false);
		return queue;
	}

	/*** 死信交换器 * @return */
	@Bean
	public Exchange exchangeDlx() {
		DirectExchange exchange = new DirectExchange("ex.pay.dlx", true, false, null);
		return exchange;
	}

	/*** 死信交换器绑定死信队列 * @return */
	@Bean
	public Binding bindingDlx() {
		return BindingBuilder.bind(queueDlx()).to(exchangeDlx()).with("key.pay.dlx").noargs();
	}

	@Autowired
	@Bean
	public RabbitTemplate rabbitTemplate(ConnectionFactory factory) {
		RabbitTemplate template = new RabbitTemplate();
		template.setConnectionFactory(factory);
		return template;

	}
}